import { h } from 'vue'

// 判断是否叶子节点
const isLeaf = (data: any, prop: any) => {
  return !(Array.isArray(data[prop]) && data[prop].length > 0)
}

// 创建 node 节点
export const renderNode = (data: any, context: any) => {
  const { props, collapsable } = context.attrs
  const cls = ['org-tree-node']
  const childNodes = []
  const children = data[props.children]

  if (isLeaf(data, props.children)) {
    cls.push('is-leaf')
  } else if (collapsable && !data[props.expand]) {
    cls.push('collapsed')
  }

  childNodes.push(renderLabel(data, context))

  if (!collapsable || data[props.expand]) {
    childNodes.push(renderChildren(children, context))
  }

  return h(
    'div',
    {
      className: cls.join(' '),
    },
    childNodes
  )
}

// 创建展开折叠按钮
export const renderBtn = (data: any, context: any) => {
  const { props } = context.attrs
  const expandHandler = context.attrs.onOnExpand
  const cls = ['org-tree-node-btn']

  if (data[props.expand]) {
    cls.push('expanded')
  }

  return h('span', {
    className: cls.join(' '),
    onClick: (e: any) => {
      e.stopPropagation()
      expandHandler && expandHandler(data)
    },
  })
}

// 创建 label 节点
export const renderLabel = (data: any, context: any): any => {
  const { props, collapsable } = context.attrs
  const label = data[props.label]
  const clickHandler = context.attrs.onOnNodeClick
  const renderContent = context.attrs['render-content']

  const childNodes = []
  if (typeof renderContent === 'function') {
    const vnode = renderContent(h, data)

    vnode && childNodes.push(vnode)
  } else {
    childNodes.push(label)
  }

  if (collapsable && !isLeaf(data, props.children)) {
    childNodes.push(renderBtn(data, context))
  }

  const cls = ['org-tree-node-label-inner']
  let { labelWidth, labelClassName } = props
  if (typeof labelWidth === 'number') {
    labelWidth = `${labelWidth}px`
  }
  if (typeof labelClassName === 'function') {
    labelClassName = labelClassName(data)
  }
  labelClassName && cls.push(labelClassName)

  return h(
    'div',
    {
      className: 'org-tree-node-label',
    },
    [
      h(
        'div',
        {
          className: cls.join(' '),
          style: { width: labelWidth },
          onClick: (e: any) => clickHandler && clickHandler(e, data),
        },
        childNodes
      ),
    ]
  )
}

// 创建 node 子节点
export const renderChildren = (list: Array<any>, context: any): any => {
  if (Array.isArray(list) && list.length > 0) {
    const children = list.map((item) => {
      return renderNode(item, context)
    })

    return h(
      'div',
      {
        className: 'org-tree-node-children',
      },
      children
    )
  }
  return ''
}

export const render = (props: any, context: any) => {
  return renderNode(props.data, context)
}

export default render
